import * as request from '../constant/fetch-request'
import HTTP_CODE from '../constant/http-code'

export const refreshHomeworkInfo = (data) => {
  return {
    type: 'GET_HOMEWORK_INFO_SUCCESS',
    data
  }
}

export const getHomeworkAnswer = (quizId) => {
  return dispatch => {
    (async () => {
      const res = await request.get(`../api/v2/homeworkQuizzes/${quizId}/answer`)
      if (res.status === HTTP_CODE.OK) {
        dispatch(refreshHomeworkInfo(res.body))
      }
    })()
  }
}

export const studentGetHomeworkAnswer = (data, callback) => {
  const {assignmentId, quizId} = data

  return dispatch => {
    (async () => {
      const res = await request.get(`../api/v2/assignments/${assignmentId}/quizzes/${quizId}/review`)
      if (res.status === HTTP_CODE.OK) {
        if (res.body.status) {
          const answerRes = await request.get(`../api/v2/assignments/${assignmentId}/quizzes/${quizId}`)
          if (answerRes.status === HTTP_CODE.OK) {
            dispatch(refreshHomeworkInfo(answerRes.body))
          }
        }
      } else {
        callback()
        dispatch(refreshHomeworkInfo({}))
      }
    })()
  }
}
